package com.jemmyee.task.web.controller.front;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.SNUtils;
import com.jemmyee.core.web.Constants;
import com.jemmyee.core.web.utils.MathUtils;
import com.jemmyee.task.entity.Task;
import com.jemmyee.task.web.TaskConstants;
import com.jemmyee.task.web.controller.kernel.BaseTaskFrontController;


/**
 * @Description:task前台Controller
 * @author:jemmyee@gmail.com
 * @date:2011-8-4
 * @version:v1.0
 */
@Controller("taskTaskFrontController")
@RequestMapping(Constants.MV_URI_APP_TASK+Constants.MV_URI_MAIN_SSL+Constants.SYM_PATH_SEPARATOR+TaskConstants.ENTITY_TASK) 
public class TaskController extends BaseTaskFrontController{
	
	private static Log log= LogFactory.getLog(TaskController.class);
	/*分页查出保存的条件*/
	private static final String ENTITY_SESSION_BEAN="admin_session_bean_"+MathUtils.getRandomDouble();
	private static final String ROOT_VIEW=Constants.MV_URI_MAIN_FRONT+Constants.MV_URI_APP_TASK+Constants.SYM_PATH_SEPARATOR+TaskConstants.ENTITY_TASK;
	private static final String ROOT_URI=Constants.MV_URI_APP_TASK+Constants.MV_URI_MAIN_SSL+Constants.SYM_PATH_SEPARATOR+TaskConstants.ENTITY_TASK;
	
	@RequestMapping("/toAdd")
	public ModelAndView toPersonal(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName(ROOT_VIEW+"/add"); 
		return mv;
	}
	@RequestMapping(Constants.MV_URI_COMM_ADD)
	@ResponseBody
	public Map<String, Object> add(@RequestBody Task bean,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		Task temp = null;
		try {
			if (taskService.findByProperty("shopUrl", bean.getShopUrl()) != null
					&& taskService.findByProperty("shopUrl", bean.getShopUrl())
							.size() > 0) {
				temp = taskService.findByProperty("shopUrl", bean.getShopUrl()).get(
						0);
			}
			if (temp != null && bean.getShopUrl().equals(bean.getShopUrl().trim())) {
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_RENAME);
			} else {
				bean.setUserId(getOnlineUser(request).getId());
				bean.setUserIP(getIP(request));
				bean.setAddTime(new Date());
				bean.setSortOrder(100);
				bean.setIsDelete((short)0);
				bean.setStatus((short)0);
				bean.setUserIP(request.getLocalAddr());
				bean.setTaskSn(SNUtils.get16NumberSNWithDate());
				taskService.save(bean);
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
			}
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}
		return model;
	}
	
	/**
	* @Description:发布的任务管理 tabs
	* @author:jemmyee@gmail.com
	* @date:2011-9-1
	*/
	@RequestMapping("/toPublishTabs")
	public ModelAndView toPublishTasks(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.addObject(Constants.MV_OBJECT_ROOT_URI, ROOT_URI);
		mv.setViewName(ROOT_VIEW+"/publish_tabs"); 
		return mv;
	}
	/**
	* @Description:接收的任务管理
	* @author:jemmyee@gmail.com
	* @date:2011-9-1
	*/
	@RequestMapping("/toReceiveTasks")
	public ModelAndView toReceiveTasks(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.addObject(Constants.MV_OBJECT_ROOT_URI, ROOT_URI);
		mv.setViewName(ROOT_VIEW+"/receive_tasks"); 
		return mv;
	}

	/**
	* @Description:任务区任务视图
	* @author:jemmyee@gmail.com
	* @date:2011-9-7
	*/
	@RequestMapping("/toTabs/{platform}")
	public ModelAndView toTabs(@PathVariable Integer platform,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.addObject(Constants.MV_OBJECT_ROOT_URI, ROOT_URI);
		mv.addObject("platform", platform);
		String sqlNew="select count(*) as "+Constants.HIBERNATE_SQL_ALIAS_COUNT+" from "+TaskConstants.TABLE_HQL_NAME_TASK+" where platform="+platform+" and status=0";
		String sqlOn="select count(*) as "+Constants.HIBERNATE_SQL_ALIAS_COUNT+" from "+TaskConstants.TABLE_HQL_NAME_TASK+" where platform="+platform+" and status=1";
		String sqlOver="select count(*) as "+Constants.HIBERNATE_SQL_ALIAS_COUNT+" from "+TaskConstants.TABLE_HQL_NAME_TASK+" where platform="+platform+" and status=2";
		String sqlAll="select count(*) as "+Constants.HIBERNATE_SQL_ALIAS_COUNT+" from "+TaskConstants.TABLE_HQL_NAME_TASK+" where platform="+platform;
		try{
			mv.addObject("countsNew",taskService.getCountByHQL(sqlNew));
			mv.addObject("countsOn",taskService.getCountByHQL(sqlOn));
			mv.addObject("countsOver",taskService.getCountByHQL(sqlOver));
			mv.addObject("countsAll",taskService.getCountByHQL(sqlAll));
		}catch (Exception e) {
			log.error(e.getMessage());
		}
		mv.setViewName(ROOT_VIEW+"/tabs"); 
		return mv;
	}
	
	
	/**
	* @Description:任务区任务
	* @author:jemmyee@gmail.com
	* @param from  menu page form
	* @type 1 taobao  2 paipai 
	* @status 0 1 2 
	* @limit 任务期限  0  24  36  48
	* @tabID 1 2 3 4...
	* @date:2011-9-7
	*/
	@RequestMapping(value ="/list/{platform}/{status}/{limit}/{tabID}/{from}/{pageSize}/{startIndex}")
	public ModelAndView list(@PathVariable Integer platform,@PathVariable Short status,@PathVariable Short limit,
			@PathVariable Integer tabID,@PathVariable String from, @PathVariable Integer pageSize,
			@PathVariable Integer startIndex, @ModelAttribute Task bean,
			HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(Task.class);
		ModelAndView mv = new ModelAndView();
		Task temp = new Task();
		if (from.equals(Constants.PAGE_ENTRY_TYPE_FORM)) {
			temp = bean;
			request.getSession().setAttribute(ENTITY_SESSION_BEAN, bean);
		}
		if (from.equals(Constants.PAGE_ENTRY_TYPE_PAGE)) {
			if (request.getSession().getAttribute(ENTITY_SESSION_BEAN) != null) {
				temp = (Task) request.getSession().getAttribute(
						ENTITY_SESSION_BEAN);
			}
		}
		if (from.equals(Constants.PAGE_ENTRY_TYPE_MENU)) {
			
		}
		if (pageSize == 0) {
			pageSize = Constants.DEFAULT_PAGESIZE;
		}
//		if (bean.getBkw() != null && !bean.getBkw().equals("")) {
//			dc.add(Restrictions.like("name", "%" + bean.getBkw() + "%"));
//		}
		if (bean.getStartTime() != null && bean.getEndTime() != null) {
			dc.add(Restrictions.ge("addTime", bean.getStartTime()));
			dc.add(Restrictions.le("addTime", bean.getEndTime()));
		}
		if (bean.getStartTime() != null && bean.getEndTime() == null) {
			dc.add(Restrictions.ge("addTime", bean.getStartTime()));
		}
		if (bean.getStartTime() == null && bean.getEndTime() != null) {
			dc.add(Restrictions.le("addTime", bean.getEndTime()));
		}
		if(platform!=-1)//所有
		{
			dc.add(Restrictions.eq("platform",platform.shortValue()));
		}
		if(status!=-1)//所有
		{
			dc.add(Restrictions.eq("status",status.shortValue()));
		}
		if(limit!=-1)//所有
		{
			dc.add(Restrictions.eq("assignTimelimit",limit.shortValue()));
		}
		dc.addOrder(Order.desc("addTime"));
		Page page = taskService.findPageByCriteria(dc, pageSize, startIndex);
		if (pageSize != 0) {
			page.setPageSize(pageSize);
		}
		temp.setHightLight(Constants.HIGHTLIGHT_PREFIX + bean.getBkw()
				+ Constants.HIGHTLIGHT_SUFFIX);
		mv.addObject("platform", platform);
		mv.addObject("status", status);
		mv.addObject("limit",limit);
		String pageURI=request.getContextPath()+Constants.SYM_PATH_SEPARATOR+ROOT_URI+"/list/"+platform+"/"+status+"/"+limit+"/"+tabID;
		initList(mv,page,"list",pageURI,ROOT_URI,temp,ROOT_VIEW,tabID,pageSize,startIndex);
		return mv;
	}
	@RequestMapping(value ="/publish_list/{status}/{tabID}/{from}/{pageSize}/{startIndex}")
	public ModelAndView publishList(
			@PathVariable Short status,@PathVariable Integer tabID,@PathVariable String from, @PathVariable Integer pageSize,
			@PathVariable Integer startIndex, @ModelAttribute Task bean,
			HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(Task.class);
		ModelAndView mv = new ModelAndView();
		Task temp = new Task();
		if (from.equals(Constants.PAGE_ENTRY_TYPE_FORM)) {
			temp = bean;
			request.getSession().setAttribute(ENTITY_SESSION_BEAN, bean);
		}
		if (from.equals(Constants.PAGE_ENTRY_TYPE_PAGE)) {
			if (request.getSession().getAttribute(ENTITY_SESSION_BEAN) != null) {
				temp = (Task) request.getSession().getAttribute(
						ENTITY_SESSION_BEAN);
			}
		}
		if (from.equals(Constants.PAGE_ENTRY_TYPE_MENU)) {

		}

		if (pageSize == 0) {
			pageSize = Constants.DEFAULT_PAGESIZE;
		}
		if (bean.getBkw() != null && !bean.getBkw().equals("")) {
			dc.add(Restrictions.like("name", "%" + bean.getBkw() + "%"));
		}
		if (bean.getStartTime() != null && bean.getEndTime() != null) {
			dc.add(Restrictions.ge("addTime", bean.getStartTime()));
			dc.add(Restrictions.le("addTime", bean.getEndTime()));
		}
		if (bean.getStartTime() != null && bean.getEndTime() == null) {
			dc.add(Restrictions.ge("addTime", bean.getStartTime()));
		}
		if (bean.getStartTime() == null && bean.getEndTime() != null) {
			dc.add(Restrictions.le("addTime", bean.getEndTime()));
		}
		if(status!=-1)//所有
		{
			dc.add(Restrictions.eq("status",status));
		}
		dc.addOrder(Order.desc("addTime"));
		Page page = taskService.findPageByCriteria(dc, pageSize, startIndex);
		if (pageSize != 0) {
			page.setPageSize(pageSize);
		}
		temp.setHightLight(Constants.HIGHTLIGHT_PREFIX + bean.getBkw()
				+ Constants.HIGHTLIGHT_SUFFIX);
		String pageURI=request.getContextPath()+Constants.SYM_PATH_SEPARATOR+ROOT_URI+"/publish_list/"+status+"/"+tabID;
		initList(mv,page,"publish_list",pageURI,ROOT_URI,temp,ROOT_VIEW,tabID,pageSize,startIndex);
		return mv;
	}

	
}
